<template>
  <div class="auth-box">
    <el-tabs v-model="loginType"
             :stretch="true"
             @tab-click="handleClick">
      <el-tab-pane label="微信登录"
                   name="wx">
        <div v-if="isauth">
          <el-result icon="success"
                     title="登录成功"
                     subTitle="请查看PC端网页">
          </el-result>
        </div>
        <div class="qrcode-box"
             v-else>
          <div v-if="isexpire"
               class="expire-box">
            二维码已过期
          </div>
          <img ref="QrCode"
               class="qrcode"
               alt="">
          <h4 align="center">用户请扫码登录</h4>
        </div>
      </el-tab-pane>
      <el-tab-pane label="账号登录"
                   name="pwdLogin">
        <div class="login-box">
          <h1 align="center"
              class="login-title">用户登录</h1>
          <el-form :model="ruleForm"
                   status-icon
                   :rules="rules_1"
                   :status-icon="true"
                   ref="ruleForm"
                   label-width="100px"
                   class="demo-ruleForm">
            <el-form-item label="用户名"
                          required
                          prop="username">
              <el-input type="text"
                        placeholder="用户名/微信名"
                        v-model="ruleForm.username"
                        autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码"
                          required
                          prop="passwd">
              <el-input type="password"
                        v-model="ruleForm.passwd"
                        :show-password="true"
                        autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="验证码"
                          required
                          prop="captcha">
              <img ref="captcha"
                   style="border: 1px solid #000;cursor:pointer;"
                   width="150"
                   height="50"
                   @click="getCaptcha2(1)">
              <span>&nbsp;&nbsp;看不清？点击更换</span>
              <el-input type="text"
                        v-model="ruleForm.captcha"
                        auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="submitForm('ruleForm')">提交</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane label="注册账号"
                   name="register">
        <div class="login-box">
          <h1 align="center"
              class="login-title">注册账号</h1>
          <el-form :model="ruleForm_2"
                   :rules="rules_2"
                   ref="ruleForm_2"
                   label-width="100px"
                   class="demo-ruleForm">
            <el-form-item label="用户头像"
                          prop="avatar">
              <upload :BizID="bizId"
                      @uploadFile="uploadFile"></upload>
            </el-form-item>
            <el-form-item label="用户名"
                          prop="username">
              <el-input v-model="ruleForm_2.username"></el-input>
            </el-form-item>
            <el-form-item label="角色">
              <el-radio v-for="(item,idx) in roleList"
                        v-model="ruleForm_2.roleId"
                        :label="item.value">{{ item.name }}</el-radio>
            </el-form-item>
            <el-form-item label="性别"
                          prop="gender">
              <el-radio v-model="ruleForm_2.gender"
                        label="男">男</el-radio>
              <el-radio v-model="ruleForm_2.gender"
                        label="女">女</el-radio>
            </el-form-item>
            <el-form-item label="年龄"
                          prop="age">
              <el-input type="number"
                        v-model="ruleForm_2.age"></el-input>
            </el-form-item>
            <el-form-item label="手机号"
                          prop="phone">
              <el-input v-model="ruleForm_2.phone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱"
                          prop="email">
              <el-input type="text"
                        v-model="ruleForm_2.email"></el-input>
            </el-form-item>
            <el-form-item label="验证码"
                          required
                          prop="captcha">
              <img ref="captcha2"
                   style="border: 1px solid #000;cursor:pointer;"
                   width="150"
                   height="50"
                   @click="getCaptcha2(2)">
              <span>&nbsp;&nbsp;看不清？点击更换</span>
              <el-input type="text"
                        v-model="ruleForm_2.captcha"
                        auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码"
                          required
                          prop="passwd">
              <el-input type="password"
                        v-model="ruleForm_2.passwd"
                        :show-password="true"
                        autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码"
                          required
                          prop="checkPass">
              <el-input type="password"
                        v-model="ruleForm_2.checkPass"
                        :show-password="true"
                        autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="doRegister('ruleForm_2')">注册</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :visible.sync="needPass"
               :center="true"
               :show-close="true"
               title="绑定密码"
               width="35%"
               :append-to-body="true">
      <el-form :model="ruleForm_3"
               :rules="rules_2"
               ref="ruleForm_3"
               label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="密码"
                      required
                      prop="passwd">
          <el-input type="password"
                    style="width: 260px"
                    v-model="ruleForm_3.passwd"
                    :show-password="true"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码"
                      required
                      prop="checkPass">
          <el-input type="password"
                    style="width: 260px"
                    v-model="ruleForm_3.checkPass"
                    :show-password="true"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="AddWxPwd('ruleForm_3')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import Upload from '@/components/upload/Upload.vue'
import { getCaptcha, getUserBizID, pwdAdd } from '@/api/user/user';

export default {
  components: {
    Upload,
  },
  props: {
    qrData: {
      type: String
    },
    isLogined: {
      type: Boolean
    },
    isExpire: {
      type: Boolean
    },
    centerDialogVisible: {
      type: Boolean
    },
    NeedPass: {
      type: Boolean
    }
  },
  watch: {
    qrData: {
      handler (newval, oldVal) {
        this.$refs.QrCode.src = newval
      }
    },
    isLogined: {
      handler (newval, oldVal) {
        this.isauth = newval;
      },
      immediate: true
    },
    isExpire: {
      handler (newval, oldVal) {
        this.isexpire = newval;
      },
    },
    centerDialogVisible: {
      handler (newval, oldVal) {
        if (newval) {
          if (this.loginType == "pwdLogin") {
            this.getCaptcha2(1);
          } else if (this.loginType == "register") {
            this.getCaptcha2(2);
          } else if (this.loginType == "wx") {
            this.$emit("getQr");
          }
        }
      }
    },
    NeedPass: {
      handler (newval, oldval) {
        this.needPass = newval;
      },
      immediate: true
    }
  },
  data () {
    var checkUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'));
      }
      var reg = /^[A-Za-z0-9_u4e00-u9fa5]{2,32}$/;
      if (!reg.test(value)) {
        return callback(new Error('用户名不能包含特殊字符'))
      }
      callback();
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        var reg = /(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/;
        if (!reg.test(value)) {
          callback(new Error('密码至少包含字母大小写加数字'));
        }
        if (value.length < 6 || value.length > 16) {
          callback(new Error('密码的长度要控制在6-16位'))
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value == this.ruleForm_2.passwd || value == this.ruleForm_3.passwd) {
        callback();
      } else {
        callback(new Error('两次输入密码不一致!'));
      }
    };
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      setTimeout(() => {
        if (value < 0 || value > 120) {
          callback(new Error('年龄必须大于0'));
        } else {
          callback();
        }
      }, 1000);
    };
    var checkEmail = (rule, value, callback) => {
      if (value.length == 0) {
        callback(new Error("邮箱不能为空"));
      }
      let regBlank = /\s+/;
      if (regBlank.test(value)) {
        callback(new Error("邮箱中不能包含空格字符"));
      }

      let regEmail = /^[\w-_]+@[\w-_]+\.[a-zA-Z]{2,}$/i;
      if (!regEmail.test(value)) {
        callback(new Error("邮箱格式错误"))
      }
      callback();
    };
    var checkPhone = (rule, value, callback) => {
      let phoneReg = /1([^12]\d{9})/;
      if (!phoneReg.test(value)) {
        callback(new Error("手机号格式错误"))
      }
      callback();
    }
    return {
      roleList: [{ name: "讲师", value: 3 }, { name: "学生", value: 2 }],
      loginType: "pwdLogin",
      tabList: ['wx', 'pwdLogin', 'register'],
      isauth: null,
      isexpire: null,
      bizId: '',
      ruleForm: {
        username: '',
        passwd: '',
        captcha: ''
      },
      ruleForm_2: {
        username: '',
        passwd: '',
        checkPass: '',
        phone: '',
        captcha: '',
        email: '',
        gender: '',
        age: null,
        avatar: '',
        roleId: 2
      },
      ruleForm_3: {
        passwd: '',
        checkPass: '',
      },
      // 登录校验使用
      rules_1: {
        username: [
          { validator: checkUserName, trigger: 'blur' }
        ],
        passwd: [
          { validator: validatePass, trigger: 'blur' }
        ]
      },
      // 注册账号使用
      rules_2: {
        username: [
          { required: true, validator: checkUserName, trigger: 'blur' }
        ],
        passwd: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        email: [
          { required: true, validator: checkEmail, trigger: 'blur' }
        ],
        age: [
          { required: true, validator: checkAge, trigger: 'blur' }
        ],
        gender: [
          { required: true, message: "请选择性别", trigger: "blur" }
        ],
        captcha: [
          { required: true, message: "验证码不能为空", trigger: "blur" }
        ],
        avatar: [
          { required: true, message: "请上传用户头像", trigger: "blur" }
        ]
      },
      needPass: false,

    }
  },
  created () {
    if (this.loginType == "pwdLogin") {
      this.getCaptcha2(1);
    }
    if (this.loginType == "register") {
      this.getCaptcha2(2);
      this.getBizID();
    }
  },
  methods: {
    async getCaptcha2 (num) {
      const ret = await getCaptcha()
      if (num == 1) {
        this.$refs.captcha.src = ret.data;
      }
      if (num == 2) {
        this.$refs.captcha2.src = ret.data;
      }
    },
    getBizID () {
      getUserBizID().then(res => {

        this.bizId = res.msg;
      }).catch(err => {
        this.$message.error(err);
      })
    },
    doRegister (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {
            userId: this.bizId,
            username: this.ruleForm_2.username,
            password: this.ruleForm_2.passwd,
            captcha: this.ruleForm_2.captcha,
            phone: this.ruleForm_2.phone,
            email: this.ruleForm_2.email,
            age: this.ruleForm_2.age,
            gender: this.ruleForm_2.gender,
            avatar: this.ruleForm_2.avatar,
            roleId: this.ruleForm_2.roleId
          }
          this.$emit("register", param, (res) => {
            if (res) {
              this.$refs[formName].resetFields();
            }
          });
        } else {
          this.$message.error('注册失败!!');
        }
      });
    },
    handleClick (tab) {
      this.loginType = this.tabList[tab.index]
      if (this.loginType === "pwdLogin") {
        this.getCaptcha2(1);
      }
      if (this.loginType == "register") {
        this.getCaptcha2(2);
        this.getBizID();
      }
      if (this.loginType === "wx") {
        this.$emit("getQr");
      }
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {
            username: this.ruleForm.username,
            password: this.ruleForm.passwd,
            captcha: this.ruleForm.captcha
          }
          this.$emit("login", param);
        } else {
          this.$message.error('登录失败!');
        }
      });
    },
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
    uploadFile (file, bizId, callback) {
      this.$tools.handleUpload(file, bizId).then(res => {
        this.ruleForm_2.avatar = res.data[0].filepath;
        callback(true);
      }).catch(err => {
        callback(false);
        this.$message.error(err);
      })
    },
    AddWxPwd (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          pwdAdd(this.ruleForm_3.passwd).then(res => {
            this.$message.success(res.msg);
            this.needPass = false;
          }).catch(err => {
            this.$message.error(err);
          })
        } else {
          this.$message.error('参数错误!!');
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
.auth-box {
  .login-box {
    width: 100%;
    height: fit-content;
    .login-title {
      height: 40px;
      line-height: 40px;
    }
    .demo-ruleForm {
      margin-top: 10px;
      .el-input {
        width: 240px;
      }
    }
  }
  .qrcode-box {
    position: relative;
    .qrcode {
      display: block;
      width: 300px;
      height: 300px;
      margin: 0 auto 10px;
      border: 1px solid rgba(0, 0, 0, 0.3);
    }
    .expire-box {
      position: absolute;
      width: 300px;
      height: 80px;
      text-align: center;
      line-height: 80px;
      left: calc(50% - 150px);
      top: 120px;
      font-size: 1.6rem;
      font-weight: 550;
      color: #f00;
      background-color: rgba(255, 255, 255, 0.5);
    }
  }
}
</style>
